/**
 * @author:linjiye
 * @date: 2025/2/5
 * @desc:
 **/

import {ImageBackground, Modal, ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import React, {useEffect, useState} from 'react'
import Animated, {FadeInDown, FadeInLeft, FadeInRight, FadeInUp} from "react-native-reanimated";
import FcButton from "@/components/FcButton";
import useGetStorage from "@/hooks/useGetStorage";
import FcModal from "@/components/FcModal";
import useSetStorage from "@/hooks/useSetStorage";
import {Flex, Provider, Toast} from "@ant-design/react-native";
import FormTitle from "@/components/FormTitle";
import FcTextInput from "@/components/FcTextInput";
import {useHeaderHeight} from "@react-navigation/elements";
import {useSafeAreaInsets} from "react-native-safe-area-context";
import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';

type Props = {}

const AnswersHistory = ({onClose,onSelectItem}: Props) => {
    const headerHeight = useHeaderHeight();
    const {top: safeTop} = useSafeAreaInsets()
    const [list, setList] = useState([])
    const [edit, setEdit] = useState(false)
    const [isEdit, setIsEdit] = useState(false)
    const [selectItem, setSelectItem] = useState({})
    const [isDelete, setIsDelete] = useState(false)

    useEffect(() => {
        getAnswersList()
    }, []);

    function getAnswersList() {
        useGetStorage('aiAnswersHistory').then(res => {
            setList(res)
            console.log(list);
        })
    }

    function handleClose() {
        onClose && onClose()
    }

    function handleEdit(val) {
        setSelectItem(val)
        setIsEdit(true)
    }

    function setName(val) {
        selectItem.name = val
        setSelectItem(selectItem)
    }
    
    function takeEdit() {
        let newList = list?.map(item => {
            if(item.id === selectItem.id) {
                return selectItem
            }
            return item
        })
        useSetStorage('aiAnswersHistory', newList).then(res => {
            getAnswersList()
            setIsEdit(false)
            Toast.info('修改成功')
        })
    }

    async function handleDown(val) {
        setSelectItem(val)
        let text = ''
        let list = val?.list || []
        list?.map((item, index) => {
            text += `${item.content}\n\n`
        })
        // const text = "这是要保存为 Word 文档的文案内容。";
        const fileName = '问答记录' + Date.now() + '.docx';
        const fileUri = FileSystem.documentDirectory + fileName;

        try {
            // 将文案内容写入文件
            await FileSystem.writeAsStringAsync(fileUri, text, {
                encoding: FileSystem.EncodingType.UTF8
            });

            // 检查是否支持分享
            if (await Sharing.isAvailableAsync()) {
                // 分享文件，用户可以选择保存
                await Sharing.shareAsync(fileUri);
                Toast.show({
                    content: '可根据情况保存',
                    duration: 3,
                    mask: false,
                })
            } else {
                console.log('分享功能不可用');
            }
        } catch (error) {
            console.error('保存文件时出错:', error);
        }
    }

    function handleDelete(val) {
        setSelectItem(val)
        setIsDelete(true)
    }

    function takeDelete() {
        let newList = list.filter(item => item.id !== selectItem.id)

        useSetStorage('aiAnswersHistory', newList).then(res => {
            getAnswersList()
            setIsDelete(false)
            Toast.info('删除成功')
        })
    }

    function handleSelectItem(item:any) {
        onSelectItem && onSelectItem(item)
    }

    return (

        <View style={styles.container}>
            <Animated.View style={styles.overlay} entering={FadeInRight.delay(1200).duration(500)}>
                <TouchableOpacity style={styles.modal_bg} onPress={() => handleClose()}></TouchableOpacity>
                <ImageBackground
                    style={styles.content}
                    source={require('@/assets/images/public/page_bg.png')}
                    resizeMode='cover'
                    entering={FadeInRight.delay(1200).duration(500)}>

                    <View style={[styles.content_wrap,{paddingTop: safeTop}]}>
                        <View style={styles.title_wrap}>
                            <Text style={styles.left}>最近问答</Text>
                            <View style={styles.right}>
                                {!edit &&
                                    <TouchableOpacity style={styles.edit_wrap} onPress={() => setEdit(true)}>
                                        <Text style={styles.edit}>编辑</Text>
                                    </TouchableOpacity>
                                }
                                {edit &&
                                    <>
                                        <TouchableOpacity onPress={() => handleClose()}>
                                            <Text style={styles.cancel}>取消</Text>
                                        </TouchableOpacity>
                                        <FcButton
                                            type='BjJB'
                                            colors={['#6989FF', '#C65EFD']}
                                            style={styles.complete_btn}
                                            itemStyle={styles.complete_btn_txt}
                                            textName='完成'
                                            onClick={() => setEdit(false)}
                                        />
                                    </>
                                }

                            </View>
                        </View>

                        <ScrollView style={styles.list_wrap} showsHorizontalScrollIndicator={false}>
                            {
                                list?.map((item, index) =>
                                    <View key={index} style={styles.item_wrap}>
                                        <TouchableOpacity onPress={() => handleSelectItem(item)}>
                                            <Text style={styles.item_txt} numberOfLines={1} ellipsizeMode="tail">{item.name}</Text>
                                        </TouchableOpacity>
                                        <View style={styles.item_right} >
                                            {!edit && <Text style={styles.item_time}>{item.time}</Text>}
                                            {edit &&
                                                <>
                                                    <TouchableOpacity onPress={() => handleEdit(item)}>
                                                        <Text style={styles.item_icon}>&#xe630;</Text>
                                                    </TouchableOpacity>
                                                    <TouchableOpacity onPress={() => handleDown(item)}>
                                                        <Text style={styles.item_icon}>&#xe666;</Text>
                                                    </TouchableOpacity>
                                                    <TouchableOpacity onPress={() => handleDelete(item)}>
                                                        <Text style={[styles.item_icon,styles.delete]}>&#xe61d;</Text>
                                                    </TouchableOpacity>
                                                </>
                                            }
                                        </View>
                                    </View>
                                )
                            }
                        </ScrollView>
                    </View>
                </ImageBackground>
            </Animated.View>

            <FcModal
                isOpen={isEdit}
                transparent
                closeShow={false}
                animationType='fade'
                onFcModalClose={() => setIsEdit(false)}
                style={styles.modal_default}
                titleText={'编辑问答'}
                titleBottomBorderWidth={0}
                footer={[
                    {
                        text: '取消',
                        onPress: () => setIsEdit(false),
                        style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
                    },
                    {
                        text: '确认',
                        onPress: () => takeEdit(),
                        style: { color: '#2856FF',fontSize: 17 },
                    },
                ]}
            >
                <View style={{paddingBottom: 20}}>
                    <FcTextInput multiline text={selectItem.name} placeholder={'请输入问答名称'}
                                 onChangeText={setName}
                                 height={82}/>
                </View>
            </FcModal>

            <FcModal
                isOpen={isDelete}
                transparent
                closeShow={false}
                animationType='fade'
                onFcModalClose={() => setIsDelete(false)}
                style={styles.modal_default}
                titleText={'是否确认删除该问答？'}
                titleBottomBorderWidth={0}
                footer={[
                    {
                        text: '取消',
                        onPress: () => setIsDelete(false),
                        style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
                    },
                    {
                        text: '确认',
                        onPress: () => takeDelete(),
                        style: { color: '#2856FF',fontSize: 17 },
                    },
                ]}
            >
                <Text style={{textAlign:'center',color: 'rgba(0,0,0,0.5)'}}>删除后，将不可恢复</Text>
            </FcModal>
        </View>

    )
}

export default AnswersHistory

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    overlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
    },
    content: {
        width: 315,
        height: '100%',
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
    },
    title_wrap: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginVertical: 16,
        marginHorizontal: 16,
        flexShrink: 0,
    },
    left: {
        fontSize: 17,
        fontWeight: 500,
        color: 'rgba(0, 0, 0, 0.9)',
    },
    right: {
        flexDirection: 'row',
        alignItems: 'center',
        gap: 10
    },
    edit_wrap:{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 8,
        backgroundColor: 'white',
        width: 48,
        height: 28,
    },
    edit: {
        fontSize: 12,
        fontWeight: 500,
        color: '#2856FF',
    },
    cancel: {
        fontSize: 15,
        fontWeight: 500,
        color: 'color: rgba(0, 0, 0, 0.5)',
        borderRadius: 8,
        width: 48,
        height: 28,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
    },
    complete_btn: {
        width: 48,
        height: 28,
    },
    complete_btn_txt: {
        fontSize: 12,
        fontWeight: 500,
        color: 'white',
        borderRadius: 8,
    },
    list_wrap: {
        marginHorizontal: 16,
        flex: 1,
    },
    item_wrap: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 12,
        borderRadius: 8,
        backgroundColor: 'white',
        paddingVertical: 12,
        paddingHorizontal: 12,
        height: 48,
    },
    item_txt: {
        fontSize: 15,
        color: 'rgba(0, 0, 0, 0.9)',
        flex: 1,
        marginRight: 10,
        width: 160
    },
    item_right: {
        flexDirection: 'row',
        alignItems: 'center',
        gap: 10,
        flexShrink: 0,
    },
    item_time: {
        fontSize: 12,
        color: 'rgba(0, 0, 0, 0.3)',
    },
    item_icon: {
        fontSize: 16,
        color: '#2856FF',
        fontFamily: 'FcIconFont',
    },
    delete: {
        color: '#FA5151',
    },

    modal_default: {
        width: 280,
        borderBottomRightRadius: 12,
        borderBottomLeftRadius: 12,
    },

    content_wrap: {
        width: '100%',
        height: '100%',
        position: 'absolute',
        top: 0,
        left: 0,
        zIndex: 100,
    },

    modal_bg: {
        width: '100%',
        height: '100%',
        position: "absolute",
        left: 0,
        bottom: 0,
    },
})